@{
ViewData["Title"] = "登录系统";
Layout = "~/Views/Shared/_LayoutLogin.cshtml";
}
<div class="container">
    <div>
        <div style="width:200px;"><h2>登录系统</h2></div>
        <div style="padding-bottom:20px;">
            <div id="down" class="btn btn-default" style="width:140px;float:right;margin-right:200px;">下载证书</div>

            <!-- <div id="isChecked" style="margin-top: 40px;">
            <h4>登录之前请进行自检</h4>

            <div id="href" class="btn btn-default" style="width:140px;">自检</div>
        </div> -->
            <div id="dd">

            </div>
        </div>
    </div>

	<div class="form-horizontal">


		
		<h4>请插入UKEY后点击按钮进行登录</h4>
		<hr />
		<div class="form-group">
			<div id="waitingPicDiv" class="col-md-offset-2 col-md-10" style="display: none">
				<img src="~/Content/waiting_transparent.gif" />
			</div>
		</div>
		<input type="hidden" id="ValidateCode" value="@ViewBag.ValidateCode" />

		<div class="form-group">
			<div class="col-md-offset-1 col-md-10 ">
				<label for="ukeySelect" class="col-sm-2 control-label"> 请选择登录的身份</label>
				<div class="col-sm-10" style="line-height: 30px;">
					<label class="radio-inline">
						<input type="radio" name="identity" value="管理员" checked> 管理员
					</label>
					<label class="radio-inline">
						<input type="radio" name="identity" value="制章人"> 制章人
					</label>
				</div>
			</div>
		</div>
		<div class="form-group">
			<div class="col-md-offset-1 col-md-10 ">
				<label for="ukeySelect" class="col-sm-2 control-label">请选择使用的UKEY</label>
				<div class="col-sm-10" style="line-height: 30px;">
					<select id="ukeySelect" name="ukeySelect" lay-filter="ukeySelect" class="form-control"></select>
				</div>
				<div class="col-sm-4" style="line-height: 30px;margin-top:10px;">
					<input id="btnLogin" type="button" class="btn btn-default" value="登录" />
				</div>
			</div>
		</div>





		<dl class="dl-horizontal">
			<dt></dt>
			<dd>
				<h4 id="h4Title" class="text-danger" style="display: none">请稍等，正在进行UKEY验证……</h4>
			</dd>
		</dl>
		<dl id="infoDiv" class="dl-horizontal" style="display: none">
			<dt>@*当前进度：*@</dt>
			<dd></dd>
		</dl>
		<div id="debug" style="display: none"></div>
	</div>

	<!-- pin码的弹窗 -->
	<div id="layerPagePinCode" style="display: none">
		<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">
			请输入PIN码：<br />
			<input type="password" name="ukeyPinCode" class="form-control" />
			<span id="pinError"></span>
		</div>
	</div>
</div>

<script src="~/js/utils.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>


<script src="~/lib/jquery/jquery-1.12.4.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/Content/layui/layui.js" charset="utf-8"></script>
<script src="~/js/dateformat.js"></script>
<script>
	  function creatediv(flag){
		if(!flag){
			var parentdiv=$('<div></div>'); //创建一个父div
			parentdiv.attr('id','isChecked'); //给父div设置id
			parentdiv.attr('style','float:right;margin-right:40px;'); //给父div设置id
			
			//console.log(parentdiv.attr("style"))
			//var childdiv=$('<h4></h4>'); //创建一个子div
			//childdiv.text("登录之前请进行自检")
			//childdiv.appendTo(parentdiv); //将子div添加到父div中
			
			var childdiv2=$('<div>自检</div>'); //创建一个子div
			childdiv2.attr('id','href'); //给子div设置id
			childdiv2.attr('class','btn btn-default'); //给子div设置id
			childdiv2.attr('style','width:140px;'); //给子div设置id
			
			childdiv2.appendTo(parentdiv); //将子div添加到父div中
			
			
			parentdiv.appendTo($("#dd")); //将父div添加到body中
		}
	
	}
	//加载列表
	function initlist(str) {
		if (str == "") {
			$("select[name='ukeySelect']").empty();
		}
		//转换成js对象并赋值
		let obj = $.parseJSON(str);
		//使失去焦点
		$("select[name='ukeySelect']").blur();
		//清空子元素
		$("select[name='ukeySelect']").empty();
		//遍历对象生成节点
		$(obj.CertInfolist).each(function(index, value) {
			// console.log(value, index);
			$("select[name='ukeySelect']").append("<option value='" + value.CertID + "'>" + value.CertCN + "</option>")
		})
	}


	//自检弹窗
	function check(UserType, makerCertID) {
		layer.open({
			btn: '自检', //按钮
			type: 1,
			title: ['警告', 'font-size:22px;color:#FF5722;'], //标题
			resize: false, //禁止调大小
			move: false, //禁止拖拽
			content: '<div style="margin-top:40px; font-size:16px;text-align:center;">请先启用自检程序,自检完成之后自动进入主菜单</div>',
			area: ['400px', '200px'], //宽和高
			//按钮点击回调
			yes: (index) => {
				$.ajax({
					type: "get",
					url: "/Login/SystemCheck",
					success: function(data) {
						if (data.data.systemChecked == 0) {
							console.log(data)
							layer.msg(data.message)
							window.sessionStorage.setItem("UserType", UserType);
							window.sessionStorage.setItem("makerCertID", makerCertID);
							window.location.href = data.data.returnUrl;
						} else {
							layer.close(index)
							layer.msg(data.data.message);
							return false;
						}
					}
				});
			},

		});
	}

	var layer = null;
	layui.use('layer', function() {
		layer = layui.layer;
	});

	$(function() {
		var isZiJian = false;
		$("#down").click(() => {
			isZiJian ? location.href = "/Login/DownCert" : layer.msg("请先自检");
		})
		console.log("@ViewBag.isChecked", "自检");

		console.log($('#ValidateCode').val(), "随机数1");

		console.log("@ViewBag.ValidateCode", "随机数2");
		if ("@ViewBag.isChecked" != "True") {
			creatediv(false);
		} else {
			
			isZiJian = true;
		}
		EnumKey(function(data) {
			initlist(data);
		}, function() {
			layer.alert("未安装UKEY支持服务！");
		});
		//键盘回车事件
		document.onkeydown = function() {
			if (event.keyCode == 13)
				$("#btnLogin").click();
		}
		$("#href").click(() => {
			$.ajax({
				type: "get",
				url: "/Login/SystemCheck",
				success: function(data) {
					if (data.data == 0) {
						$("#isChecked").hide();
						isZiJian = true;
						console.log(data)
						layer.msg(data.message)
					} else {
						isZiJian = false;
						layer.close(index)
						layer.msg(data.data.message);
						return false;
					}
				}
			});
		});
		//随机数
		console.log($('#ValidateCode').val());
		//登录点击事件
		$('#btnLogin').click(function() {
			if (!isZiJian) {
				layer.msg("请先自检");
				return;
				// check(0, certSN);
			}
			// console.log($("#ukeySelect").val());
			//选择ukey的value
			var certSN = $("#ukeySelect").val();
			console.log(certSN);
			if (certSN == null || certSN == '') {
				layer.msg("未选择ukey")
				return;
			}
			//使用淡入效果来显示一个隐藏的 <p> 元素
			$("#h4Title").fadeIn(); //显示正在验证
			$("#infoDiv").fadeIn(); //显示当前进度
			var base64 = new Base64();
			DisplayMessage("正在获取UKEY证书");
			layer.open({
				type: 1,
				title: false //不显示标题栏
					,
				closeBtn: true,
				area: '300px;',
				shade: 0.8,
				id: 'LAY_InputPin' //设定一个id，防止重复弹出
					,
				btn: ['确定'],
				btnAlign: 'c',
				moveType: 1 //拖拽模式，0或者1
					,
				content: $("#layerPagePinCode").html(),
				yes: function(index, layero) {
					//签名验证,如果验证成功执行第二个参数
					VerifyPin(JSON.stringify({
							CertID: certSN,
							//输入的pin码
							Pin: layero.find("input[name='ukeyPinCode']").val()
						}),
						function(verifyPinRet) {
							//如果验证失败
							if (verifyPinRet != "Ok") {
								layero.find("#pinError").html("Pin码错误，请重新输入");
								layero.find("input[name='ukeyPinCode']").val("");
							} else {
								$("input[name='ukeyPinCode']").val(layero.find("input[name='ukeyPinCode']").val());
								layer.close(index); //关闭弹窗
								DisplayMessage("正在进行签名挑战");
								var hashInput = {
									CertID: certSN,
									DataBase64: base64.encode($("#ValidateCode").val())
								};
								ComputeHash(JSON.stringify(hashInput),
									function(hashRet) {
										var hashRetObject = JSON.parse(hashRet);
										if (hashRetObject.error != "Ok") {
											DisplayMessage("计算哈希失败");
											return;
										}
										var sigInput = {
											CertID: certSN,
											HashBase64: hashRetObject.hash,
											StrPin: $("input[name='ukeyPinCode']").val()
										};
										// console.log(JSON.stringify(sigInput));
										SignByHash(JSON.stringify(sigInput),
											function(sigRet) {
												var sigRetObject = JSON.parse(sigRet);
												if (sigRetObject.error != "Ok") {
													DisplayMessage("计算签名失败");
													return;
												}

												EncryptCertList((data) => {
													console.log(data);
													data = JSON.parse(data);
													// let CertID = data.CertInfolist[0].CertID;
													 let CertID = null;
													//获取选中的ID值
													$(data.CertInfolist).each((i, value) => {
														if (value.CertCN == $("#ukeySelect option:selected").text()) {
															CertID = value.CertID
														}
													})
													var str = JSON.stringify({
														CertID: certSN,
														ValidateCode: $("#ValidateCode").val()
													});
													console.log(base64.encode(str), "11111")
													var External = {
														CertID: CertID,
														//编码
														DataBase64: base64.encode(str)
													};
													ExternalEncrypt(JSON.stringify(External), (data) => {
														data = JSON.parse(data);
														if (data.error == "Ok") {
															var dataToPost = {
																// ArrayNo: CertID,
																EncryptData: data.contentBase64
															};
															if ($("input[name='identity']:checked").val() == "制章人") {
																$.post("/Login/SignMakerLogin", dataToPost, function(res) {
																	console.log(res);
																	if (res.state == 404) {
																		layer.msg(res.message);
																	} else {

																		window.sessionStorage.setItem("UserType", 0);
																		window.sessionStorage.setItem("makerCertID", certSN);
																		window.location.href = res.returnUrl;



																	}
																})
															} else if ($("input[name='identity']:checked").val() == "管理员") {
																$.post("/Login/Login", dataToPost, function(res) {
																	if (res.state == 404) {
																		layer.msg(res.message);
																	} else {
																		window.sessionStorage.setItem("UserType", 1);
																		window.sessionStorage.setItem("makerCertID", certSN);
																		window.location.href = res.returnUrl;



																	}
																})
															}
														}
													});
												})

												//window.localStorage.setItem('certSN', sigInput.CertID);


											});

									});

							}
						});
				},
				cancel: function() {
					$("#h4Title").hide();
					$("#infoDiv").empty();
				}
			});

		});
	});
</script>
